var User = require('../model/user');
var _ = require('underscore');

var Mp3 = require('../model/mp3')

exports.index = function(req, res) {
    Mp3.fetch(function(err, mp3s) {
        if (err) {
            console.log(err)
        } else {
            res.render('pages/index', {
                mp3s: mp3s
            });
        }
    });
}

/**
 * 注册页面
 */
exports.signup = function(req, res) {
    res.render('pages/signup');
}

/**
 * 保存用户
 */
exports.save = function(req, res) {
    var userObj = req.body.user;
    if (userObj) {
        var user = new User(userObj);
        user.save(function(err) {
            if (err) {
                console.log(err)
            } else {
                res.redirect('signin');
            }
        });
    } else {
        res.render('pages/signup');
    }
}

exports.profile=function(req,res){
    res.render('pages/profile')
}

/**
 * 用户资料修改
 */

exports.update = function(req, res) {
    var userObj = req.body.user;
    var id = req.body.user._id;
    User.findOneByAttr({
        _id: id
    }, function(err, user) {
        if (err) {
            console.log(err)
        }
        var _user = _.extend(user, userObj)
        _user.face = req.file.filename
        _user.save(function(err, user) {
            if (err) {
                console.log(err);
            }
            //更新session中的User数据
            req.session.user = user;
            res.redirect('/profile');
        });
    })
}

/**
 * 登陆页面
 */
exports.signin = function(req, res) {
    res.render('pages/signin');
}

exports.login = function(req, res) {
    var userObj = req.body.user;
    if (userObj) {
        User.findOneByAttr({
            email: userObj.email
        }, function(err, user) {
            if (err) {
                console.log(err)
            } else {
                if (user.password == userObj.password) {
                    req.session.user = user;
                    res.redirect('/');
                } else {
                    console.log('密码不一致')
                    res.redirect('/signin');
                }
            }
        });
    } else {
        res.render('pages/signin');
    }
}


/**
 * 登出
 */
exports.logout = function(req, res) {
    delete req.session.user
    res.redirect('/')
}

/**
 * 判断用户是否登陆
 */
exports.signinRequired = function(req, res, next) {
    var _user = req.session.user

    if (!_user) {
        return res.redirect('/signin');
    }
    next();

}

/**
 * 判断用户是否为管理员
 */
exports.adminRequired = function(req, res, next) {
    var _user = req.session.user
    console.log(_user)
    if (_user.role != 1) {
        return res.redirect('/signin')
    }
    next()

}
